package com.xueersi.interactivevideoeditor.viewModels
{	
	import com.xueersi.interactivevideoeditor.manager.GlobalApplication;
	import com.xueersi.interactivevideoeditor.model.ImageElement;
	import com.xueersi.interactivevideoeditor.model.InteractiveVisualElement;
	
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	[Event(name="visualElementChange",type="flash.events.Event")]
	[Event(name="visualElementReady",type="flash.events.Event")]
	public class ImageObject extends Component
	{
		private var _imageEle:ImageElement;
		private var _displayContent:DisplayObject;
		
		public function ImageObject()
		{
			super();
		}
		
		public function set imageEle(value:ImageElement):void
		{
			_imageEle = value;
			_imageEle.facade = this;
			load();
			dispatchEvent(new Event("visualElementChange",true));
		}
				
		public function load():void
		{
			var loader:Loader = new Loader();
			var onComplete:Function = function(event:Event):void
			{
				loader.removeEventListener(Event.COMPLETE,onComplete);
				processAfterLoaded(loader.contentLoaderInfo.content);
			}
			
			var onProgress:Function = function(event:ProgressEvent):void
			{
				trace("[total: ]" + event.bytesTotal + " loaded ");
			}
				
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
			var url:String = String(_imageEle.resource.getRelation());
			if(!_imageEle.resource.isLocal)
				url = GlobalApplication.RESOURCE_BASE_PATH + url;
			loader.load(new URLRequest(url));
		}
		
		private function onIOError(event:IOErrorEvent):void
		{
			trace("[" + this.id + "]" + event.text);
		}
		
		public function setSize(width:Number,height:Number):void
		{
		
		}	
		
		public function processAfterLoaded(content:DisplayObject):void
		{
			_displayContent = content;
			addChild(_displayContent);
			
			dispatchEvent(new Event("visualElementReady",true));
		}	
		
		override public function updateElement():void
		{
			super.updateElement();
			// todo updateElement;
			trace("updateElement");
		}	
	}
}